package com.dy.yunying.biz.controller.manage;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.dy.yunying.api.dto.AccountManageDTO;
import com.dy.yunying.api.dto.AccountProhibitDTO;
import com.dy.yunying.api.entity.WanProhibitLog;
import com.dy.yunying.api.entity.WanUser;
import com.dy.yunying.api.entity.WanUserThird;
import com.dy.yunying.api.enums.AccountRegSrcEnum;
import com.dy.yunying.api.vo.AccountInfoVO;
import com.dy.yunying.api.vo.AccountManageVO;
import com.dy.yunying.api.vo.AccountOperateInfoVO;
import com.dy.yunying.biz.service.manage.AccountManageService;
import com.dy.yunying.biz.service.manage.WanProhibitLogService;
import com.dy.yunying.biz.service.manage.WanUserService;
import com.dy.yunying.biz.service.manage.WanUserThirdService;
import com.dy.yunying.biz.utils.DateUtils;
import com.pig4cloud.pig.admin.api.dto.SysUserInfo;
import com.pig4cloud.pig.admin.api.feign.RemoteUserService;
import com.pig4cloud.pig.common.core.constant.SecurityConstants;
import com.pig4cloud.pig.common.core.exception.BusinessException;
import com.pig4cloud.pig.common.core.mybatis.Page;
import com.pig4cloud.pig.common.core.util.R;
import com.sjda.framework.common.ResultData;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 用户账户管理
 * @author sunyq
 * @date 2022/8/18 18:19
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/accountManage")
public class AccountManageController {

	private final AccountManageService accountManageService;

	private final WanUserService wanUserService;

	private final WanUserThirdService wanUserThirdService;

	private final WanProhibitLogService wanProhibitLogService;

	private final RemoteUserService remoteUserService;

	@RequestMapping("/list")
	public R getPage(@RequestBody AccountManageDTO accountManageDTO){
		if (StringUtils.isEmpty(accountManageDTO.getStartTime()) || StringUtils.isEmpty(accountManageDTO.getEndTime())){
			return R.failed("请选择时间");
		}
		Page<AccountManageVO> result= accountManageService.selectWanUserPageByCondition(accountManageDTO);
		return R.ok(result);
	}

	@RequestMapping("/selectAccountInfo")
	public R selectAccountInfo(Long  userId){
		if (userId == null){
			return R.failed("账户不能为空");
		}

		WanUser wanUser = wanUserService.getById(userId);
		if (wanUser == null){
			return R.failed("当前账户不存在！");
		}
		List<WanUserThird> thirds = wanUserThirdService.list(Wrappers.<WanUserThird>lambdaQuery().eq(WanUserThird::getUserId, wanUser.getUserid())
				.eq(WanUserThird::getUsername, wanUser.getUsername()).eq(WanUserThird::getStatus, 1)
		);
		AccountInfoVO accountInfoVO = new AccountInfoVO();
		convertBean(wanUser,accountInfoVO);
		if (CollectionUtils.isNotEmpty(thirds)){
			boolean taptap = false;
			boolean qq = false;
			for (WanUserThird third : thirds) {
				if ("taptap".equalsIgnoreCase(third.getThirdCode())) {
					taptap = true;
				} else if ("qq".equalsIgnoreCase(third.getThirdCode())){
					qq = true;
				}
			}
			if (taptap){
				accountInfoVO.setTaptap("已绑定");
			}

			if (qq){
				accountInfoVO.setQq("已绑定");
			}
		}
		return R.ok(accountInfoVO);
	}

	private void convertBean(WanUser wanUser, AccountInfoVO accountInfoVO) {
		accountInfoVO.setAccount(wanUser.getUsername());
		accountInfoVO.setRegArea(StringUtils.isEmpty(wanUser.getProvince()) ? "-" : wanUser.getProvince()+"/"+wanUser.getCity());
		accountInfoVO.setLastActiveTime(DateUtils.dateToString(wanUser.getLogintime(),DateUtils.YYYY_MM_DD_HH_MM_SS));
		accountInfoVO.setNickName(StringUtils.isEmpty(wanUser.getNickname()) ? "-" : wanUser.getNickname());
		accountInfoVO.setPhoneNumber(StringUtils.isEmpty(wanUser.getMobile()) ? "未绑定" : wanUser.getMobile());

		accountInfoVO.setRegSrc(StringUtils.isEmpty(AccountRegSrcEnum.getName(wanUser.getRegsrc()))? "-":AccountRegSrcEnum.getName(wanUser.getRegsrc()));
		String realName = wanUser.getRealname();
		String idCard = wanUser.getIdcard();

		if (StringUtils.isNotEmpty(realName) && StringUtils.isNotEmpty(idCard)){
			String realNameStr = realName.substring(0, 1);
			int length = idCard.length();
			String mid= "";
			for (int i = 0; i <length-7 ; i++) {
				mid = mid+"*";
			}
			accountInfoVO.setRealName(realNameStr+"*/"+idCard.substring(0,3)+mid+idCard.substring(length-4));
		} else {
			accountInfoVO.setRealName("未认证");
		}
		accountInfoVO.setRegIp(StringUtils.isEmpty(wanUser.getRegip()) ? "-" : wanUser.getRegip());
		accountInfoVO.setRegTime(DateUtils.dateToString(wanUser.getRegtime(),DateUtils.YYYY_MM_DD_HH_MM_SS));
		accountInfoVO.setUserId(wanUser.getUserid());
		accountInfoVO.setQq("未绑定");
		accountInfoVO.setTaptap("未绑定");
	}


	@RequestMapping("/accountOperateInfo")
	public R accountOperateInfo(String account){
		if (StringUtils.isEmpty(account)){
			return R.failed("账户名不能为空");
		}
		List<AccountOperateInfoVO> result = new ArrayList<>();
		List<WanProhibitLog> list = wanProhibitLogService.list(Wrappers.<WanProhibitLog>lambdaQuery().eq(WanProhibitLog::getContent, account)
				.eq(WanProhibitLog::getType, 1).orderByDesc(WanProhibitLog::getCreateTime));
		if (CollectionUtils.isNotEmpty(list)){
			List<Integer> ids = list.stream().map(wanProhibitLog -> Integer.valueOf(wanProhibitLog.getCreator() + "")).collect(Collectors.toList());
			R<List<SysUserInfo>> userInfoByIds = remoteUserService.getUserInfoByIds(SecurityConstants.FROM_IN, ids);
			List<SysUserInfo> sysUserInfos = userInfoByIds.getData();
			for (WanProhibitLog wanProhibitLog : list) {
				AccountOperateInfoVO accountOperateInfoVO = new AccountOperateInfoVO();
				BeanUtils.copyProperties(wanProhibitLog,accountOperateInfoVO);
				if (null != sysUserInfos) {
					for (SysUserInfo sysUserInfo : sysUserInfos) {
						if (sysUserInfo.getUserId().intValue() == accountOperateInfoVO.getCreator().intValue()){
							accountOperateInfoVO.setCreatorName(sysUserInfo.getUserName());
						}
					}
				}
				result.add(accountOperateInfoVO);
			}
		}
		return R.ok(result);
	}


	@RequestMapping("/export")
	public R export(@RequestBody AccountManageDTO accountManageDTO, HttpServletResponse response){
		accountManageDTO.setCurrent(1L);
		accountManageDTO.setSize(9999999L);
		if (StringUtils.isEmpty(accountManageDTO.getKpiValue())){
			accountManageDTO.setKpiValue("regtime");
		}
		if (StringUtils.isEmpty(accountManageDTO.getSort())){
			accountManageDTO.setSort("desc");
		}
		try {

			WriteCellStyle headWriteCellStyle = new WriteCellStyle();
			//设置背景颜色
			headWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
			//设置头字体
			WriteFont headWriteFont = new WriteFont();
			headWriteFont.setFontHeightInPoints((short)13);
			headWriteFont.setBold(true);
			headWriteCellStyle.setWriteFont(headWriteFont);
			//设置头居中
			headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);

			//内容策略
			WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
			//设置 水平居中
			contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
			HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);

			String sheetName = "用户账户管理";
			Page<AccountManageVO> result= accountManageService.selectWanUserPageByCondition(accountManageDTO);
			response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
			response.setCharacterEncoding("utf-8");
			String fileName = URLEncoder.encode("用户账户管理-" + DateUtils.getCurrentTimeNoUnderline(), "UTF-8").replaceAll("\\+", "%20");
			response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
			response.setHeader("file-name", fileName);
			ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).registerWriteHandler(horizontalCellStyleStrategy).build();
			WriteSheet writeSheet0 = EasyExcel.writerSheet(0, sheetName).registerWriteHandler(horizontalCellStyleStrategy).head(AccountManageVO.class).build();
			excelWriter.write(result.getRecords(), writeSheet0);
			excelWriter.finish();
		} catch (Exception e) {
			log.error("用户账户管理导出异常, 异常原因：{}",e);
			throw new BusinessException("导出异常");
		}
		return null;
	}

	/**
	 * 新增封禁
	 *
	 * @return
	 */
	@RequestMapping("/addAccountProhibit")
	public R add(@RequestBody AccountProhibitDTO accountProhibitDTO) {
		try {
			String content = accountProhibitDTO.getContent();
			Integer time = accountProhibitDTO.getTime();

			// 参数校验
			if (StringUtils.isBlank(content) || Objects.isNull(time)) {
				return R.failed("传入参数不合法");
			}
			if (time == null || time < 0) {
				accountProhibitDTO.setTime(0);
			}else if(time > 0){
				Integer newTime = time*24*60;
				accountProhibitDTO.setTime(newTime);
			}
			accountProhibitDTO.setType(1);
			accountProhibitDTO.setStatus(1);
			accountProhibitDTO.setRemark("封禁当前账号");
			R r = accountManageService.addAccountProhibit(accountProhibitDTO);

			return r;
		} catch (BusinessException e) {
			log.error("新增封禁异常：", e);
			return R.failed(ResultData.StatusEnum.ERROR.getStatus(), e.getCode(), e.getMessage());
		} catch (Exception e) {
			log.error("新增封禁异常：", e);
			return R.failed(ResultData.StatusEnum.ERROR);
		}
	}


	/**
	 * 解封
	 *
	 * @return
	 */
	@RequestMapping(value = "/accountLeft")
	public R accountLeft(@RequestBody AccountProhibitDTO req) {
		try {
			String content = req.getContent();

			// 参数校验
			if (StringUtils.isBlank(content)) {
				return R.failed(ResultData.StatusEnum.ERROR.getStatus(), "参数不合法");
			}
			R r = accountManageService.accountLeft(req);
			return r;
		} catch (BusinessException e) {
			log.error("批量解封异常：", e);
			return R.failed(ResultData.StatusEnum.ERROR.getStatus(), e.getCode(), e.getMessage());
		} catch (Exception e) {
			log.error("批量解封异常：", e);
			return R.failed(ResultData.StatusEnum.ERROR);
		}

	}



}
